const express = require('express')
const fs = require('fs')
const pathLib = require('path')
const common = require('../../libs/common')
const mysql = require('mysql')
const db = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: '123456789',
  database: 'learner'
})

module.exports = function () {
  let router = express.Router()

  router.get('/', (req, res) => {
    switch (req.query.act) {
      case 'del':
        // 文件操作
        db.query(`SELECT * FROM customer_evaluation_table WHERE id='${req.query.id}'`, (err, data) => {
          if (err) {
            console.error(err)
            res.status(500).send('database error').end()
          } else {
            if (data.length === 0) {
              res.status(404).send('no this customer_evaluation').end()
            } else {
              fs.unlink('static/upload/' + data[0].src, err => {
                if (err) {
                  console.error(err)
                  res.status(500).send('file opration').end()
                } else {
                  // 删除操作
                  db.query(`DELETE FROM customer_evaluation_table WHERE id='${req.query.id}'`, (err, data) => {
                    if (err) {
                      console.error(err)
                      res.status(500).send('database error').end()
                    } else {
                      res.redirect('/admin/custom')
                    }
                  })
                }
              })
            }
          }
        })
        break
      case 'mod':
        db.query(`SELECT * FROM customer_evaluation_table`, (err, evaluations) => {
          if (err) {
            console.error(err)
            res.status(500).send('database error').end()
          } else {
            db.query(`SELECT * FROM customer_evaluation_table WHERE id='${req.query.id}'`, (err, data) => {
              if (err) {
                console.error(err)
                res.status(500).send('database error').end()
              } else if (data.length === 0) {
                res.status(404).send('no this customer_evaluation').end()
              } else {
                res.render('admin/custom.ejs', { evaluations, mod_data: data[0] })
              }
            })
          }
        })
        break
      default:
        db.query(`SELECT * FROM customer_evaluation_table`, (err, evaluations) => {
          if (err) {
            console.error(err)
            res.status(500).send('database error').end()
          } else {
            res.render('admin/custom.ejs', { evaluations })
          }
        })
    }
  })

  router.post('/', (req, res) => {
    let title = req.body.title
    let description = req.body.description
    // 文件上传处理
    let ext = ''  // 扩展名
    let oldPath = ''
    let newPath = ''
    let newFileName = ''
    if (req.files[0]) {
      ext = pathLib.parse(req.files[0].originalname).ext  // 扩展名
      oldPath = req.files[0].path
      newPath = req.files[0].path + ext
      newFileName = req.files[0].filename + ext
    } else {
      newFileName = null
    }

    if (newFileName) {
      fs.rename(oldPath, newPath, err => {
        if (err) {
          console.error(err)
          res.status(500).send('file opration error').end()
        } else {
          if (req.body.mod_id) {
            // 删除旧头像
            db.query(`SELECT * FROM customer_evaluation_table WHERE id='${req.body.mod_id}'`, (err, data) => {
              if (err) {
                console.error(err)
                res.status(500).send('database error').end()
              } else if (data.length === 0) {
                res.status(404).send('old file not found').end()
              } else {
                fs.unlink('static/upload/' + data[0].src, err => {
                  if (err) {
                    console.error(err)
                    res.status(500).send('file opration').end()
                  } else {
                    db.query(`UPDATE customer_evaluation_table SET title='${title}', description='${description}', src='${newFileName}' WHERE id=${req.body.mod_id}`, (err, data) => {
                      if (err) {
                        console.error(err)
                        res.status(500).send('database error').end()
                      } else {
                        res.redirect('/admin/custom')
                      }
                    })
                  }
                })
              }
            })
            // 增加新头像
          } else {
            db.query(`INSERT INTO customer_evaluation_table (title, description, src) VALUE ('${title}', '${description}', '${newFileName}')`, (err, data) => {
              if (err) {
                console.error(err)
                res.status(500).send('database error').end()
              } else {
                res.redirect('/admin/custom')
              }
            })
          }
        }
      })
    } else {
      if (req.body.mod_id) {
        db.query(`UPDATE customer_evaluation_table SET title='${title}', description='${description}' WHERE id=${req.body.mod_id}`, (err, data) => {
          if (err) {
            console.error(err)
            res.status(500).send('database error').end()
          } else {
            res.redirect('/admin/custom')
          }
        })
      } else {
        db.query(`INSERT INTO customer_evaluation_table (title, description, src) VALUE ('${title}', '${description}', '${newFileName}')`, (err, data) => {
          if (err) {
            console.error(err)
            res.status(500).send('database error').end()
          } else {
            res.redirect('/admin/custom')
          }
        })
      }
    }
  })

  return router
}
